using OpenSource.SpreadsheetFactory;
using System;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace OpenSource.SpreadsheetFactory.Internal
{
    internal abstract class Column<T>
    {
        protected bool IsSpreadsheetColumn { get; set; }
        protected abstract MemberInfo Member { get; }
        internal string Title { get; set; }
        internal int Ordinal { get; set; }

        public Column(MemberInfo member)
        {
            SpreadsheetColumnAttribute attribute = Attribute.GetCustomAttribute(member, typeof(SpreadsheetColumnAttribute)) as SpreadsheetColumnAttribute;
            if (attribute == null)
            {
                this.IsSpreadsheetColumn = false;
            }
            else
            {
                this.IsSpreadsheetColumn = true;
                this.Title = attribute.Title;
                this.Ordinal = attribute.Ordinal;
            }
        }

        public static Column<T> CreateColumn(MemberInfo memberInfo)
        {
            Column<T> column = Column<T>.GetFieldColumn(memberInfo as FieldInfo);
            if (column == null)
            {
                column = Column<T>.GetPropertyColumn(memberInfo as PropertyInfo);
            }
            if (!((column == null) || column.IsSpreadsheetColumn))
            {
                column = null;
            }
            return column;
        }

        internal abstract Type GetColumnType();
        internal abstract object GetColumnValue(T instance);

        private static Column<T> GetFieldColumn(FieldInfo fieldInfo)
        {
            if (fieldInfo == null)
            {
                return null;
            }
            return new FieldColumn<T>(fieldInfo);
        }

        private static Column<T> GetPropertyColumn(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null)
            {
                return null;
            }
            return new PropertyColumn<T>(propertyInfo);
        }
    }
}

